<template>
  <div class="trigger-rich-text">
    <!-- 富文本编辑器 -->
    <base-editor ref="editor" class="msg-email__editor" v-model="content" :max-length="5000" :is-trigger="isTrigger" @input="getInput" @rangeIndex="getRangeIndex"></base-editor>
    <!-- 选择字段 -->
    <div class="select-modules">
      <span class="from-biz-type">{{ fromBizTypeName }} {{ FieldSuffixText }}</span>
      <el-select v-model="selectField" :placeholder="$t('common.wiki.selectField')">
        <el-option v-for="item in selectFields" :key="item.fieldValue" :label="item.fieldName" :value="item.fieldValue"></el-option>
      </el-select>
      <el-button type="primary" @click="addField">{{ $t('common.wiki.insertField') }}</el-button>
    </div>
  </div>
</template>
<script>
import { t } from '@src/locales'
import { isNotUndefined } from '@src/util/type';
let rangeIndex = -1;
const FieldSuffixText = `- ${t('common.connector.field')}`
export default {
  name: 'rich_text-search',
  props: {
    value: {
      type: String,
      default: '',
    },
    field: {
      type: Object,
      default: () => {},
    },
    // 是否是触发器
    isTrigger: {
      type: Boolean,
      default: false
    },
  },
  computed: {
    fromBizTypeName() {
      return this.field?.setting?.fromBizTypeName || '' 
    },
    selectFields() {
      return this.field?.setting?.templateFields?.[0]?.fieldList || [] 
    }
  },
  data() {
    return {
      FieldSuffixText,
      selectField: '',
      content: this.value,
    }
  },
  methods: {
    // 获取带格式的编辑器内容<p>xxx</p>
    getInput (html) {
      this.content = html;
      // 更新知识库表单值
      this.$emit('update', this.content)
      return true;
    },
    getRangeIndex(index){
      rangeIndex = index;
    },
    // 插入字段
    addField(){
      
      if(!this.selectField) return this.$message.warning(this.$t('common.wiki.selectFieldValidate'));
      
      let content = this.content;
      if(rangeIndex < 0) rangeIndex = content.length;
      if (content && content.indexOf(this.selectField) > -1) return this.$message.warning(this.$t('common.wiki.insertFieldValidate'));
      
      // 获取光标位置
      const selectionIndex = this.$refs.editor.getSelection();
      
      // 如果光标位置存在，就在光标位置插入，否则就在最后插入
      if (isNotUndefined(selectionIndex)) {
        rangeIndex = selectionIndex;
      } else {
        rangeIndex = content.length;
      }
      
      // 插入字段文本
      const text = ` {${this.selectField}} `
      // 插入数据
      this.$refs.editor.insertText(rangeIndex, text)
      // 获取插入后的html
      const getHtml = this.$refs.editor.getHtml();
      // 更新数据
      this.content = getHtml
      // 更新知识库表单值
      this.$emit('update', this.content)
    },
  },
};
</script>
